@echo off
chcp 65001 >nul
title WanKe ERP System Stopper

echo ====================================
echo      WanKe ERP System Stopper
echo ====================================
echo.

set ERROR_OCCURRED=0

:: Stop Nginx service
echo [STOP] Stopping Nginx service...
tasklist | findstr nginx >nul
if %errorlevel% == 0 (
    taskkill /f /im nginx.exe >nul 2>&1
    if %errorlevel% == 0 (
        echo [SUCCESS] Nginx service stopped
    ) else (
        echo [ERROR] Failed to stop Nginx service
        set ERROR_OCCURRED=1
    )
) else (
    echo [INFO] Nginx service is not running
)

:: Stop Java backend service
echo [STOP] Stopping backend service...
set JAVA_STOPPED=0

:: Method 1: Stop by process name
for /f "tokens=2" %%i in ('tasklist /fi "imagename eq java.exe" /fo table /nh ^| findstr jeecg-system-start') do (
    taskkill /f /pid %%i >nul 2>&1
    if %errorlevel% == 0 (
        set JAVA_STOPPED=1
    )
)

:: Method 2: Find and stop Java process by port
setlocal enabledelayedexpansion
for /f "tokens=5" %%i in ('netstat -ano ^| findstr :8080') do (
    tasklist /fi "pid eq %%i" | findstr java >nul
    if !errorlevel! == 0 (
        taskkill /f /pid %%i >nul 2>&1
        if !errorlevel! == 0 (
            echo [SUCCESS] Backend service stopped (PID: %%i)
            set JAVA_STOPPED=1
        ) else (
            echo [ERROR] Failed to stop backend service (PID: %%i)
            set ERROR_OCCURRED=1
        )
    )
)

if %JAVA_STOPPED% == 0 (
    echo [INFO] Backend service is not running
)

:: Wait a moment for processes to fully terminate
timeout /t 2 /nobreak >nul

:: Check if services are stopped
echo [CHECK] Checking service status...
tasklist | findstr nginx >nul
if %errorlevel% == 0 (
    echo [WARNING] Nginx process is still running
    set ERROR_OCCURRED=1
) else (
    echo [SUCCESS] Nginx service completely stopped
)

netstat -ano | findstr :8080 >nul
if %errorlevel% == 0 (
    echo [WARNING] Port 8080 is still in use
    set ERROR_OCCURRED=1
) else (
    echo [SUCCESS] Backend service completely stopped
)

echo.
if %ERROR_OCCURRED% == 0 (
    echo ====================================
    echo WanKe ERP System Stopped Successfully!
    echo ====================================
    echo.
    echo Window will close automatically in 3 seconds...
    timeout /t 3 /nobreak >nul
    exit /b 0
) else (
    echo ====================================
    echo WanKe ERP System Stop Failed!
    echo Some services may still be running.
    echo ====================================
    echo.
    echo Press any key to close this window...
    pause >nul
    exit /b 1
)
